package com.tech.ioc;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Description:
 * 1. bean作用域 https://www.w3cschool.cn/wkspring/nukv1ice.html
 * 2.
 * @Author: zl
 * @Date: 2019/5/23 14:13
 */
public class SpringBeanExam {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springBeanExam.xml");


    /**
     * bean作用域singleton：单例在spring IoC容器仅存在一个Bean实例，Bean以单例方式存在，默认值
     */
    @Test
    public void beanScopeBySingleton() {

        HelloWorldBean beanA = (HelloWorldBean)context.getBean("helloWorldSingleton");
        beanA.setMessage("this is scope is singleton");
        beanA.getMessage();

        HelloWorldBean beanB = (HelloWorldBean)context.getBean("helloWorldSingleton");
        beanB.getMessage();
        System.out.println(beanA==beanB);
    }

    /**
     * bean作用域protoType：每次从容器中调用Bean时，都返回一个新的实例，即每次调用getBean()时，相当于执行newXxxBean()
     */
    @Test
    public void beanScopeByPrototype() {
        HelloWorldBean beanA = (HelloWorldBean)context.getBean("helloWorldProtoType");
        beanA.setMessage("this is bean scope protoType");
        beanA.getMessage();

        HelloWorldBean beanB = (HelloWorldBean)context.getBean("helloWorldProtoType");
        beanB.getMessage();

    }

    /**Bean 后置处理器允许在调用初始化方法前后对 Bean 进行额外的处理。
     *
     * bean生命周期：定义-初始化 - 使用 - 销毁
     */
    @Test
    public void beanLifeCycle(){
        HelloWorldBean bean = (HelloWorldBean) context.getBean("helloWorldLifeCycle");
        bean.setMessage("hello world");
        bean.getMessage();
        context.registerShutdownHook();
    }

    /**
     * bean 继承
     */
    @Test
    public void beanExtends(){
        // 父bean
        System.out.println(" bean extends begin-------------");
        HelloWorldBean bean = (HelloWorldBean) context.getBean("helloWorldBean");
        //bean.getMessage();
        //子bean
        SubHelloWorldBean subBean= (SubHelloWorldBean) context.getBean("subHelloWorldBean");
        subBean.getMessage();// 继承自父类
        subBean.getMessage1();// 子类自己扩展
        System.out.println(" bean extends end-------------");
    }
}
